<?php
class PictureTable extends Doctrine_Table
{
//    public function createSelect($required = true, $multiple = false)
//    {
//        $pairs = $this->fetchPairs('id', 'name');
//        $select = new Zend_Form_Element_Select('picture_id', array('multiple' => $multiple));
//        $select
//            ->setRequired($required)
//            ->addMultioption('0', '---Select picture---')
//            ->addMultiOptions($pairs)
//            ->setLabel('Picture');
//        return $select;
//    }
//
//    public function fetchPairs($key = 'id', $name = 'name')
//    {
//        $query = $this->createQuery()
//            ->select($key.', '.$name)
//            ->orderBy($name)
//            ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
//            ;
//
//        $rows = $query->execute();
//
//        $pairs = array();
//        foreach ($rows as $row)
//            $pairs[$row[$key]] = $row[$name];
//
//        return $pairs;
//    }

    public function fetchExtGridData($params)
    {
    	// Ważne - ustawiamy offset na podstawie page i limit !!!
    	$params['offset'] = $params['limit']*$params['page'] - $params['limit'];

        $query = Doctrine_Query::create()
            ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
            ->from('Picture p')
            ->leftJoin('p.article a')
            ;

        //filter on article ID
        if($params['article_id'])
            $query->addWhere('a.id = ?', $params['article_id'])
            ;

        $query_cnt = clone $query;

        $query_cnt
            ->select('COUNT(DISTINCT p.id) cnt')
            ;

        $query
            ->select('p.title, p.place, p.created_at, p.position, a.title')
            ->orderBy($params['sort'].' '.$params['dir'])
            ->limit($params['limit'])
            ->offset($params['offset'])
            ;

        $rawData = array();

        $pictures = $query->execute();
        $count = $query_cnt->fetchOne();

        //liczymy ile mamy stron
        if( $count > 0 )
        	$total_pages = ceil($count['cnt']/(int)$params['limit']);
        else
        	$total_pages = 0;

        if ($params['page'] > $total_pages)
            $params['page'] = $total_pages;

//        $i = 0;
//        foreach($pictures as $row)
//        {
//            $rawData['rows'][$i]['id'] = $row['id'];
//            $rawData['rows'][$i]['cell'] = array($row['id'], $row['title'], $row['place'], $row['created_at']);
//            $i++;
//        }
        
        $rawData['rows'] = $pictures;           //tu dajemy wynik zapytania
        $rawData['records'] = $count['cnt'];    //tu dajemy liczbe rekordów
        $rawData['page'] = $params['page'];     //tu dajemy nr strony
        $rawData['total'] = $total_pages;       //tu dajemy liczbę stron

        return $rawData;
    }
}
?>